package net.fdukedom.epicurus.client.plugin.core.panels;

import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;

import net.fdukedom.epicurus.client.ClientSession;
import net.fdukedom.epicurus.client.connection.MessageServiceWrapper;
import net.fdukedom.epicurus.client.plugin.core.CoreClientPlugin;
import net.fdukedom.epicurus.client.ui.GUIDispatcher;
import net.fdukedom.epicurus.client.ui.GridBagJPanel;
import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.resource.ResourceDispatcher;
import net.fdukedom.epicurus.service.interaction.IdentificationRequest;
import net.fdukedom.epicurus.service.interaction.IdentificationRequestWriter;
import net.fdukedom.epicurus.service.interaction.ProfileXMLWrapper;
import net.fdukedom.epicurus.service.interaction.ResponseReader;

public class ProfilePanel extends GridBagJPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * User name text field
	 */
	private JTextField userNameField;

	/**
	 * Sex combo box
	 */
	private JComboBox sexComboBox;

	/**
	 * Action listener for saving connection options
	 * 
	 * @author Alexander Kirakozov
	 */
	private class SaveActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			User user = ClientSession.getInstance().getUser();

			user.setName(userNameField.getText());
			user.setSex((short) sexComboBox.getSelectedIndex());

			UserHelper.getInstance().saveUser(user);
		}
	}

	/**
	 * Action listener for updating user local profile
	 * 
	 * @author Alexander Kirakozov
	 */
	private class UpdateActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			User user = ClientSession.getInstance().getUser();
			IdentificationRequestWriter request = new IdentificationRequestWriter(
					IdentificationRequest.ID_UPDATE);

			request.setPluginName(CoreClientPlugin.PLUGINNAME);
			request.setEmail(user.getEmail());
			request.setPassword(user.getPassword());

			MessageServiceWrapper service = new MessageServiceWrapper();

			String xmlResponse = service.sendMessage(request.toString());
			ResponseReader reader = new ResponseReader(xmlResponse);

			if (reader.getStatus()) {
				ProfileXMLWrapper wrap = new ProfileXMLWrapper(reader
						.getResult().getChild(ProfileXMLWrapper.PROFILE));

				user.setSex(wrap.getSex());
				user.setName(wrap.getNickName());
				UserHelper.getInstance().saveUser(user);

				sexComboBox.setSelectedIndex(wrap.getSex());
				userNameField.setText(wrap.getNickName());
			} else {
				GUIDispatcher.getInstance()
						.showInfoMessage(reader.getMessage());
			}
		}
	}

	/**
	 * Action listener for updatin user profile on server
	 * 
	 * @author Alexander Kirakozov
	 */
	private class CommitActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			User user = ClientSession.getInstance().getUser();

			// Send to the server
			IdentificationRequestWriter request = new IdentificationRequestWriter(
					IdentificationRequest.ID_COMMIT);

			request.setPluginName(CoreClientPlugin.PLUGINNAME);
			request.setEmail(user.getEmail());
			request.setPassword(user.getPassword());
			request.addParameter(new ProfileXMLWrapper(userNameField.getText(),
					(short) sexComboBox.getSelectedIndex()).getElement());

			MessageServiceWrapper service = new MessageServiceWrapper();

			String xmlResponse = service.sendMessage(request.toString());
			ResponseReader reader = new ResponseReader(xmlResponse);

			if (reader.getStatus()) {
				GUIDispatcher.getInstance()
						.showInfoMessage(reader.getMessage());

				// Save localy
				user.setName(userNameField.getText());
				user.setSex((short) sexComboBox.getSelectedIndex());
				UserHelper.getInstance().saveUser(user);
			} else {
				GUIDispatcher.getInstance().showErrMessage(reader.getMessage());
			}
		}
	}

	/**
	 * Constructor
	 */
	public ProfilePanel() {
		init();
	}

	/**
	 * Initialize panel
	 */
	private void init() {
		ResourceBundle profileBundle = ResourceDispatcher.getInstance()
				.getBundle("bundles.common.Profile");

		// Fields
		final int[] widths = { 50, 50, 50, 50, 50 };
		final int[] heights = { 5, 20, 5, 20, 5, 20, 0 };
		final double[] yWeights = { 0, 0, 0, 0, 0, 0, 1 };
		initLayout(null, widths, yWeights, heights);

		// Configuration fields & labels
		User user = ClientSession.getInstance().getUser();

		addComponent(new JLabel(profileBundle
				.getString("common.profile.userName")), 1, 1, 2, 1,
				GridBagConstraints.FIRST_LINE_END);
		userNameField = new JTextField(user.getName());
		addComponent(userNameField, 1, 2, 3, 1,
				GridBagConstraints.FIRST_LINE_START);

		String[] sexStrings = {
				profileBundle.getString("common.profile.sex.undefinied"),
				profileBundle.getString("common.profile.sex.male"),
				profileBundle.getString("common.profile.sex.female") };
		addComponent(new JLabel(profileBundle.getString("common.profile.sex")),
				3, 1, 2, 1, GridBagConstraints.FIRST_LINE_END);
		sexComboBox = new JComboBox(sexStrings);
		sexComboBox.setSelectedIndex(user.getSex());
		addComponent(sexComboBox, 3, 2, 3, 1,
				GridBagConstraints.FIRST_LINE_START);

		// Buttons
		JButton button = new JButton("Commit");
		button.addActionListener(new CommitActionListener());
		addComponent(button, 5, 1, 1, 1, GridBagConstraints.FIRST_LINE_START);

		button = new JButton("Update");
		button.addActionListener(new UpdateActionListener());
		addComponent(button, 5, 2, 1, 1, GridBagConstraints.PAGE_START);

		button = new JButton("Save");
		button.addActionListener(new SaveActionListener());
		addComponent(button, 5, 3, 1, 1, GridBagConstraints.FIRST_LINE_END);
	}
}
